<?php

require_once dirname(__FILE__).'/../lib/indicadoresGeneratorConfiguration.class.php';
require_once dirname(__FILE__).'/../lib/indicadoresGeneratorHelper.class.php';

/**
 * indicadores actions.
 *
 * @package    plagas
 * @subpackage indicadores
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class indicadoresActions extends autoIndicadoresActions
{
  public function executeListEjecutar(sfWebRequest $request)
  {
     $id = $request->getParameter('id');
     $this->getUser()->setAttribute('ids', $id);
     $this->redirect('reales/new?id='.$id);
  }
  
  public function executeCreate(sfWebRequest $request)
  {
    $this->form = $this->configuration->getForm();

    $this->indicador = $this->form->getObject();

    //
    $this->validarIndicador($request);
    //

    $this->processForm($request, $this->form);

    $this->setTemplate('indicador');//$this->setTemplate('new');
}

  protected function executeBatchEjecutar(sfWebRequest $request)
  {
      $ids = $request->getParameter('ids');
      $this->getUser()->setAttribute('ids', $ids);
      $this->redirect('reales/new');
  }

  //VALIDAR CONSULTA SQL (NUMERADOR Y DENOMINADOR)
  protected function validarIndicador(sfWebRequest $request)
  {
    $allFormValues = $request->getParameter($this->form->getName());
    $num = $allFormValues["numerador"];
    $den = $allFormValues["denominador"];

    //VALIDO QUE LAS CONSULTAS SQL (NUMERADOR Y DENOMINADOR) SEAN CORRECTAS
    if ($this->validarSQL($den) == 'error')
    {
        $this->getUser()->setFlash('error', sprintf('Error en la consulta del denominador'));
        $this->redirect('indicadores/new');
    }
    if ($this->validarSQL($num) == 'error')
    {
        $this->getUser()->setFlash('error', sprintf('Error en la consulta del numerador'));
        $this->redirect('indicadores/new');
    }
}

  protected function validarSQL($consulta)
  {
    $statement = Doctrine_Manager::getInstance()->connection();

    try
    {
         $results = $statement->execute($consulta);
//            $results = Doctrine_Manager::getInstance()->getCurrentConnection()->fetchAssoc($consulta);
    }
    catch (Exception $exc)
    {
//            echo $exc->getTraceAsString();
        return "error";
    }
    // paso a un arreglo el resultado de la consulta.
    return $results->fetchAll();
}

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $notice = $form->getObject()->isNew() ? 'The item was created successfully.' : 'The item was updated successfully.';

      try {
        $indicador = $form->save();
      } catch (Doctrine_Validator_Exception $e) {

        $errorStack = $form->getObject()->getErrorStack();

        $message = get_class($form->getObject()) . ' has ' . count($errorStack) . " field" . (count($errorStack) > 1 ?  's' : null) . " with validation errors: ";
        foreach ($errorStack as $field => $errors) {
            $message .= "$field (" . implode(", ", $errors) . "), ";
        }
        $message = trim($message, ', ');

        $this->getUser()->setFlash('error', $message);
        return sfView::SUCCESS;
      }

      $this->dispatcher->notify(new sfEvent($this, 'admin.save_object', array('object' => $indicador)));

      if ($request->hasParameter('_save_and_add'))
      {
        $this->getUser()->setFlash('notice', $notice.' You can add another one below.');

        $this->redirect('@indicador_new');
      }
      else if ($request->hasParameter('_save_and_list'))
      {
          $this->getUser()->setFlash('notice', $notice);
          $this->redirect('indicador');
      }
      else
      {
        $this->getUser()->setFlash('notice', $notice);

        $this->redirect(array('sf_route' => 'indicador_edit', 'sf_subject' => $indicador));
      }
    }
    else
    {
      $this->getUser()->setFlash('error', 'The item has not been saved due to some errors.', false);
    }
  }

  public function executeDelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();

    $this->dispatcher->notify(new sfEvent($this, 'admin.delete_object', array('object' => $this->getRoute()->getObject())));
    if ($this->getRoute()->getObject()->getObjetivos()->count() != 0 || $this->getRoute()->getObject()->getReales()->count() != 0 || $this->getRoute()->getObject()->getHijos()->count() != 0)
    {
        $this->getUser()->setFlash('error', 'No se puede eliminar el indicador.');
        $this->redirect('@indicador');
    }
    if ($this->getRoute()->getObject()->delete())
    {
      $this->getUser()->setFlash('notice', 'The item was deleted successfully.');
    }

    $this->redirect('@indicador');
  }
}
